package com.ruoyi.result.longitudinalProjects.service.impl;

import java.util.*;
import java.util.stream.Collectors;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.sql.SqlUtil;
import com.ruoyi.result.longitudinalProjects.domain.ResultLongitudinalProjects;
import com.ruoyi.result.longitudinalProjects.domain.dto.ResultLongitudinalProjectsDTO;
import com.ruoyi.result.longitudinalProjects.domain.vo.ResultLongitudinalProjectsVO;
import com.ruoyi.result.longitudinalProjects.mapper.ResultLongitudinalProjectsMapper;
import com.ruoyi.result.longitudinalProjects.service.IResultLongitudinalProjectsService;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.SysUserPostMapper;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.team.trash.domain.AchievementTrash;
import com.ruoyi.team.trash.mapper.AchievementTrashMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 纵向课题Service业务层处理
 *
 * @author ruoyi
 * @date 2025-01-22
 */
@Service
public class ResultLongitudinalProjectsServiceImpl implements IResultLongitudinalProjectsService
{
    @Autowired
    private ResultLongitudinalProjectsMapper resultLongitudinalProjectsMapper;

    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysUserRoleMapper sysUserRoleMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private AchievementTrashMapper achievementTrashMapper;
    /**
     * 查询纵向课题
     *
     * @param id 纵向课题主键
     * @return 纵向课题
     */
    @Override
    public ResultLongitudinalProjects selectResultLongitudinalProjectsById(Long id)
    {
        return resultLongitudinalProjectsMapper.selectResultLongitudinalProjectsById(id);
    }

    @Override
    public List<ResultLongitudinalProjectsVO> selectResultLongitudinalProjectsByIds(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return Collections.emptyList();
        }
        List<ResultLongitudinalProjects> resultLongitudinalProjectsList = resultLongitudinalProjectsMapper.selectResultLongitudinalProjectsByIds(ids);
        List<ResultLongitudinalProjectsVO> resultLongitudinalProjectsVOList = new ArrayList<>();

        for (ResultLongitudinalProjects resultPaper : resultLongitudinalProjectsList) {
            ResultLongitudinalProjectsVO resultLongitudinalProjectsVO = new ResultLongitudinalProjectsVO();
            // 假设 resultLongitudinalProjects 和 resultLongitudinalProjectsVO 有相同的字段，先进行复制
            BeanUtils.copyProperties(resultPaper, resultLongitudinalProjectsVO);

            // 根据 userId 查询 nick_name
            SysUser sysUser = sysUserMapper.selectUserById(resultPaper.getUserId());
            if(sysUser != null){
                resultLongitudinalProjectsVO.setNickName(sysUser.getNickName());
            }

            resultLongitudinalProjectsVOList.add(resultLongitudinalProjectsVO);
        }
        return resultLongitudinalProjectsVOList;
    }

    @Override
    public ResultLongitudinalProjects getLongitudinalById(Long id) {
        if (id == null) {
            return null;
        }
        return resultLongitudinalProjectsMapper.selectLongitudinalById(id);
    }

    /**
     * 查询纵向课题列表
     *
     * @param resultLongitudinalProjects 纵向课题
     * @return 纵向课题
     */
    @Override
    public TableDataInfo selectResultLongitudinalProjectsList(ResultLongitudinalProjectsDTO dto) {
        LoginUser loginUser = SecurityUtils.getLoginUser();
        Long deptId = loginUser.getUser().getDeptId();

        // 判断是否为超级管理员（若依默认超级管理员用户ID为1）
        boolean isSuperAdmin = loginUser.getUser().getUserId().equals(1L);

        // 非超级管理员才进行部门过滤
        if (!isSuperAdmin) {
            dto.setDeptId(deptId);
        }

        // 分页
        PageDomain pageDomain = TableSupport.buildPageRequest();
        if (StringUtils.isNotNull(pageDomain.getPageNum()) && StringUtils.isNotNull(pageDomain.getPageSize())) {
            String orderBy = SqlUtil.escapeOrderBySql(pageDomain.getOrderBy());
            PageHelper.startPage(pageDomain.getPageNum(), pageDomain.getPageSize(), orderBy)
                    .setReasonable(pageDomain.getReasonable());
        }

        // 查询纵向课题列表（按部门过滤）
        List<ResultLongitudinalProjects> list = resultLongitudinalProjectsMapper.selectResultLongitudinalProjectsListByDept(dto);

        // 转换VO并填充用户昵称
        List<ResultLongitudinalProjectsVO> voList = list.stream().map(r -> {
            ResultLongitudinalProjectsVO vo = new ResultLongitudinalProjectsVO();
            BeanUtils.copyProperties(r, vo);
            if (r.getUserId() != null) {
                SysUser sysUser = sysUserMapper.selectUserById(r.getUserId());
                if (sysUser != null) {
                    vo.setNickName(sysUser.getNickName());
                }
            }
            return vo;
        }).collect(Collectors.toList());

        // 返回表格数据
        TableDataInfo rspData = new TableDataInfo();
        rspData.setCode(HttpStatus.SUCCESS);
        rspData.setMsg("查询成功");
        rspData.setTotal(new PageInfo(list).getTotal());
        rspData.setRows(voList);
        return rspData;
    }
    /**
     * 新增纵向课题
     *
     * @param resultLongitudinalProjects 纵向课题
     * @return 结果
     */
    @Override
    public int insertResultLongitudinalProjects(ResultLongitudinalProjects resultLongitudinalProjects)
    {
        return resultLongitudinalProjectsMapper.insertResultLongitudinalProjects(resultLongitudinalProjects);
    }

    /**
     * 修改纵向课题
     *
     * @param resultLongitudinalProjects 纵向课题
     * @return 结果
     */
    @Override
    public int updateResultLongitudinalProjects(ResultLongitudinalProjects resultLongitudinalProjects)
    {
        return resultLongitudinalProjectsMapper.updateResultLongitudinalProjects(resultLongitudinalProjects);
    }

    /**
     * 批量删除纵向课题
     *
     * @param ids 需要删除的纵向课题主键
     * @return 结果
     */
    @Override
    public int deleteResultLongitudinalProjectsByIds(Long[] ids)
    {
        List<ResultLongitudinalProjects> resultLongitudinalProjectsList = resultLongitudinalProjectsMapper.selectResultLongitudinalProjectsByIds(ids);
        for (ResultLongitudinalProjects resultLongitudinalProjects : resultLongitudinalProjectsList) {
            AchievementTrash achievementTrash = new AchievementTrash();
            achievementTrash.setUserid(resultLongitudinalProjects.getUserId());
            achievementTrash.setAchievementType("纵向课题");
            achievementTrash.setTitle(resultLongitudinalProjects.getProjectName());
            achievementTrash.setAchievementId(resultLongitudinalProjects.getId());
            achievementTrash.setDeletedAt(new Date());
            achievementTrashMapper.insertAchievementTrash(achievementTrash);
        }
        return resultLongitudinalProjectsMapper.deleteResultLongitudinalProjectsByIds(ids);
    }

    /**
     * 删除纵向课题信息
     *
     * @param id 纵向课题主键
     * @return 结果
     */
    @Override
    public int deleteResultLongitudinalProjectsById(Long id)
    {
        return resultLongitudinalProjectsMapper.deleteResultLongitudinalProjectsById(id);
    }
}
